package org.dromara.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.open.bean.result.WxFastMaSetNickameResult;
import me.chanjar.weixin.open.bean.result.WxOpenResult;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.platform.domain.TMiniProgramBaseInfo;
import org.dromara.platform.domain.bo.TMiniProgramBaseInfoBo;
import org.dromara.platform.domain.vo.TMiniProgramAuthenticationVo;
import org.dromara.platform.domain.vo.TMiniProgramBaseInfoVo;
import org.dromara.platform.domain.vo.TMiniProgramCategoryVo;
import org.dromara.platform.domain.vo.TMiniProgramDomainVo;
import org.dromara.platform.mapper.*;
import org.dromara.platform.service.ITMiniProgramBaseInfoService;
import org.dromara.wechat.constants.WechatConstants;
import org.dromara.wechat.enums.WechatEnums;
import org.dromara.wechat.service.WechatOpenService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 小程序基础信息Service业务层处理
 *
 * @author Lion Li
 * @date 2025-06-04
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class TMiniProgramBaseInfoServiceImpl implements ITMiniProgramBaseInfoService {

    private final TMiniProgramBaseInfoMapper baseMapper;
    private final TEnterpriseInfoMapper enterpriseInfoMapper;
    private final TMiniProgramDomainMapper domainMapper;
    private final TMiniProgramCategoryMapper categoryMapper;
    private final TMiniProgramAuthenticationMapper authenticationMapper;
    private final WechatOpenService wechatOpenService;


    /**
     * 查询小程序基础信息
     *
     * @param id 主键
     * @return 小程序基础信息
     */
    @Override
    public TMiniProgramBaseInfoVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询小程序基础信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 小程序基础信息分页列表
     */
    @Override
    public TableDataInfo<TMiniProgramBaseInfoVo> queryPageList(TMiniProgramBaseInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TMiniProgramBaseInfo> lqw = buildQueryWrapper(bo);
        Page<TMiniProgramBaseInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的小程序基础信息列表
     *
     * @param bo 查询条件
     * @return 小程序基础信息列表
     */
    @Override
    public List<TMiniProgramBaseInfoVo> queryList(TMiniProgramBaseInfoBo bo) {
        LambdaQueryWrapper<TMiniProgramBaseInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TMiniProgramBaseInfo> buildQueryWrapper(TMiniProgramBaseInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TMiniProgramBaseInfo> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(TMiniProgramBaseInfo::getId);
        lqw.eq(bo.getEnterpriseId() != null, TMiniProgramBaseInfo::getEnterpriseId, bo.getEnterpriseId());
        lqw.eq(StringUtils.isNotBlank(bo.getAppid()), TMiniProgramBaseInfo::getAppid, bo.getAppid());
        lqw.like(StringUtils.isNotBlank(bo.getNickName()), TMiniProgramBaseInfo::getNickName, bo.getNickName());
        lqw.like(StringUtils.isNotBlank(bo.getShortName()), TMiniProgramBaseInfo::getShortName, bo.getShortName());
        lqw.eq(StringUtils.isNotBlank(bo.getHeadImageUrl()), TMiniProgramBaseInfo::getHeadImageUrl, bo.getHeadImageUrl());
        lqw.eq(bo.getSearchStatus() != null, TMiniProgramBaseInfo::getSearchStatus, bo.getSearchStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getBlurb()), TMiniProgramBaseInfo::getBlurb, bo.getBlurb());
        lqw.eq(bo.getStatus() != null, TMiniProgramBaseInfo::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增小程序基础信息
     *
     * @param bo 小程序基础信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TMiniProgramBaseInfoBo bo) {
        TMiniProgramBaseInfo add = MapstructUtils.convert(bo, TMiniProgramBaseInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改小程序基础信息
     *
     * @param bo 小程序基础信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TMiniProgramBaseInfoBo bo, Long userId) {
        // 调用微信接口更新小程序信息
        setNickName(bo, userId);
        TMiniProgramBaseInfo update = MapstructUtils.convert(bo, TMiniProgramBaseInfo.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TMiniProgramBaseInfo entity){
        //TODO 做一些数据校验,如唯一约束

    }

    /**
     * 校验并批量删除小程序基础信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 查询小程序详情
     *
     * @param
     * @return 查询小程序详情
     */
    @Override
    public TMiniProgramBaseInfoVo getAppDetails(TMiniProgramBaseInfoBo bo) {
        //小程序详情
        TMiniProgramBaseInfoVo result = new TMiniProgramBaseInfoVo();
        //企业ID
        result.setQyId(bo.getEnterpriseId());
        if (!Objects.isNull(bo.getId())) {
            //小程序ID
            result.setId(bo.getId());
            TMiniProgramDomainVo miniProgramDomainVo=domainMapper.selectBaseId(bo.getId());
            if(miniProgramDomainVo!=null){
                //域名ID和业务域名
                result.setYmId(miniProgramDomainVo.getId());
                result.setWebViewDomain(miniProgramDomainVo.getWebViewDomain());
            }
            List<TMiniProgramCategoryVo> miniProgramCategoryVoList=categoryMapper.selectBaseId(bo.getId());
            if (CollectionUtils.isNotEmpty(miniProgramCategoryVoList)) {
                result.setHasCategory(true);
            } else {
                result.setHasCategory(false);
            }
            TMiniProgramAuthenticationVo miniProgramAuthenticationVo = authenticationMapper.selectBaseId(bo.getId());
            if(miniProgramAuthenticationVo!=null){
                //认证ID
                result.setRzId(miniProgramAuthenticationVo.getId());
            }
        }
        return result;
    }

    @Override
    public Long getCountByEnterpriseId(Long enterpriseId, Integer status) {
        return baseMapper.selectCount(Wrappers.<TMiniProgramBaseInfo>lambdaQuery().eq(TMiniProgramBaseInfo::getEnterpriseId, enterpriseId).eq(TMiniProgramBaseInfo::getStatus, status));
    }

    @Override
    public List<TMiniProgramBaseInfoVo> getAppName(Long enterpriseId) {
        return baseMapper.getAppName(enterpriseId);
    }

    @Override
    public R setNickName(TMiniProgramBaseInfoBo bo, Long userId) {
        // 查询是否变更小程序名称
        TMiniProgramBaseInfo baseInfo = baseMapper.selectById(bo.getId());
        if (baseInfo.getNickName().equals(bo.getNickName())) {
            return R.fail("小程序名称未变更");
        }
        String redisValue = bo.getAppid() + "_" + bo.getNickName() + "_" + userId;
        String redisKey = WechatConstants.NICKNAME_CHECK_PREFIX + redisValue;
        try {
            Object obj = RedisUtils.getCacheObject(redisKey);
            if (obj != null) {
                throw new RuntimeException("检测到频繁提交，请稍后再试");
            }
            RedisUtils.setCacheObject(redisKey, redisValue);
            WxFastMaSetNickameResult result = wechatOpenService.setNickName(bo.getAppid(), bo.getNickName());
            // todo setNickName失败，返回审核单id，用于查询改名审核状态
            if (null != result && !WechatEnums.SUCCESS.getCode().equals(result.getErrcode())) {
                return R.fail(result.getErrmsg());
            } else if (WechatEnums.SUCCESS.getCode().equals(result.getErrcode())) {
                // todo 改名成功，更新数据库
                baseMapper.updateNiceName(bo.getId(), bo.getNickName());
            }
        } catch (Exception e) {
            RedisUtils.deleteObject(redisKey);
            log.error("设置微信昵称失败", e.getMessage());
            throw new ServiceException(e.getMessage());
        }
        RedisUtils.deleteObject(redisKey);
        return R.ok();
    }

    @Override
    public R setSignature(TMiniProgramBaseInfoBo bo, Long userId) {
        try {
            // 查询是否变更小程序介绍
            TMiniProgramBaseInfo baseInfo = baseMapper.selectById(bo.getId());
            if (baseInfo.getBlurb().equals(bo.getBlurb())) {
                return R.fail("小程序介绍未变更");
            }
            WxOpenResult result = wechatOpenService.setSignature(bo.getAppid(), bo.getBlurb());
            if (null != result && !WechatEnums.SUCCESS.getCode().equals(result.getErrcode())) {
                return R.fail(result.getErrmsg());
            } else if (WechatEnums.SUCCESS.getCode().equals(result.getErrcode())) {
                TMiniProgramBaseInfo update = new TMiniProgramBaseInfo();
                update.setId(bo.getId());
                update.setRemark(bo.getRemark());
                baseMapper.updateById(update);
            }
        } catch (Exception e) {
            log.error("设置微信介绍失败", e.getMessage());
            throw new ServiceException(e.getMessage());
        }
        return R.ok();
    }
}
